<template>
  <search-table
      :page-pos="pagePos"
    :data="partList"
    :columns="partCol"
    :page.sync="queryParams.pageIndex"
    :size.sync="queryParams.pageSize"
    :total="partTotal"
    :loading="partListLoading"
    @queryFun="getNewData">
    <template slot="search">
      <Button type="primary" ghost class="md-add-jh" @click="showModal(null)">创建部件</Button>
      <Button type="primary" v-if="$route.query.productId" ghost class="md-add-jh" @click="relativePart(false)">关联部件</Button>
      <Button type="primary" v-if="$route.query.productId" ghost class="md-add-jh" @click="relativePart(true)">关联公共部件</Button>
      <Divider type="vertical" style="margin: 10px 0px 10px 10px;" />
      <Select filterable clearable v-model="queryParams.partType" @on-change="selectPart" placeholder="部件类型" style="margin-left: 15px;width: 150px">
        <Option v-for="item in formPartTypeOptions" :key="item.value" :value="item.value">{{item.label}}</Option>
      </Select>
      <Input v-model.trim="queryParams.name"  clearable placeholder="部件名称" @on-change="searchPartName" style="width: 180px;margin-left: 15px" />
      <Button class="header-btn" type="primary" ghost style="height: 32px;margin-left: 5px;" @click="refreshPartList()">
        <i class="el-icon-refresh-right" />
      </Button>
    </template>
    <!--创建镜像"-->

    <Modal v-model="modalData.show" :mask-closable="false" width="600"
           :title="`${isUpgrade ? '升级' : isAdd ? '创建部件' : '修改部件'}`"
           @on-visible-change="changeVisible"
           >
      <Form ref="formInline" :model="formInline" :rules="ruleInline" :label-width="120" style="width: 500px">
        <FormItem prop="upgradeType" label="部件升级方式" v-if="isUpgrade" key="upgradeType">
          <RadioGroup v-model="upgradeType">
            <Radio label="add">新建部件</Radio>
            <Radio label="relevance">关联部件</Radio>
          </RadioGroup>
        </FormItem>
        <template v-if="upgradeType === 'add'">
          <FormItem prop="name" label="部件名称" key="name">
            <Input clearable v-model="formInline.name"></Input>
          </FormItem>
          <FormItem prop="type" label="软硬件" key="type">
            <Select filterable transfer filterable clearable v-model="formInline.type" placeholder="" :disabled="!isAdd && !isUpgrade">
              <Option v-for="(item, index) in typeOptions" :value="index" :key="index">{{ item }}</Option>
            </Select>
          </FormItem>
          <!-- 软件需要上传软件包 -->
          <template v-if="formInline.type === 0">
            <FormItem  label="软件包文件" prop="fileId" key="fileId">
              <itemUpload ref="fileUpload"
                          @upload-success="val=>uploadSuccess(val,'file')"
                          :formatArr="['zip']"
                          :showUploadList="true"
                          uploadText="上传文件"
                          @clearFile="setClear('file')"
                          fileType="files"></itemUpload>
            </FormItem>
            <FormItem  label="语言" prop="language" key="language">
              <Select filterable transfer filterable clearable v-model="formInline.language" placeholder="">
                <Option :value="1">JAVA</Option>
                <Option :value="2">GO</Option>
                <Option :value="3">PHP</Option>
                <Option :value="4">PYTHON</Option>
                <Option :value="5">C语言</Option>
                <Option :value="6">NODE.JS</Option>
                <Option :value="7">C++</Option>
                <Option :value="99">其他</Option>
              </Select>
            </FormItem>
            <FormItem  label="包类别" prop="packageType" key="packageType">
              <Select filterable transfer filterable clearable v-model="formInline.packageType" placeholder="">
                <Option :value="1">源码</Option>
                <Option :value="2">执行包</Option>
                <Option :value="3">安装包</Option>
                <Option :value="4">固件包</Option>
                <Option :value="5">基线检测工具</Option>
                <Option :value="6">补丁包</Option>
              </Select>
            </FormItem>
          </template>
          <FormItem prop="partType"  label="部件类型" key="partType">
            <Select filterable transfer filterable clearable v-model="formInline.partType" placeholder="">
              <Option v-for="item in formPartTypeOptions" :value="item.value" :key="item.value">{{ item.label }}</Option>
            </Select>
          </FormItem>
          <FormItem prop="version" label="版本号" key="version">
            <Input clearable v-model="formInline.version"></Input>
          </FormItem>
          <FormItem prop="supplier" label="供应商" key="supplier">
            <Input clearable v-model="formInline.supplier"></Input>
          </FormItem>
          <FormItem prop="model" label="型号" key="model">
            <Input clearable v-model="formInline.model"></Input>
          </FormItem>
          <FormItem prop="groupAddress" label="包URL" key="groupAddress">
            <Input clearable v-model="formInline.groupAddress"></Input>
          </FormItem>
          <FormItem prop="enumItem" label="CPE名称" class="my-form-item" key="enumItem">
            <Input clearable v-model="formInline.enumItem"></Input>
            <Tooltip style="margin-left: 10px;" transfer max-width="200" content="通用平台枚举，是指MITRE或者NIST提供的CPE V2.2或者CPE V2.3的URI" placement="top">
              <Icon type="ios-alert" class="ios-alert" />
            </Tooltip>
          </FormItem>
          <FormItem prop="swid" label="软件标识标签" class="my-form-item" key="swid">
            <Input clearable v-model="formInline.swid"></Input>
            <Tooltip style="margin-left: 10px;" transfer max-width="200" content="由软件厂商提供的按照ISO/IEC 19770-2:2015规范的标记识别符" placement="top">
              <Icon type="ios-alert" class="ios-alert" />
            </Tooltip>
          </FormItem>
          <FormItem prop="objectId" label="对象标识" key="objectId">
            <Input clearable v-model="formInline.objectId"></Input>
          </FormItem>
          <FormItem prop="fileName" label="文件名称" key="fileName">
            <Input clearable v-model="formInline.fileName"></Input>
          </FormItem>
          <FormItem prop="description"  label="描述" key="description">
            <Input clearable v-model="formInline.description" type="textarea" :rows="3"></Input>
          </FormItem>
          <FormItem prop="md5"  label="MD5" key="md5">
            <Input clearable v-model="formInline.md5" type="textarea" :rows="3"></Input>
          </FormItem>
          <FormItem prop="sha1"  label="SHA1" key="sha1">
            <Input clearable v-model="formInline.sha1" type="textarea" :rows="3"></Input>
          </FormItem>
          <FormItem prop="sha256"  label="SHA256" key="sha256">
            <Input clearable v-model="formInline.sha256" type="textarea" :rows="3"></Input>
          </FormItem>
          <FormItem prop="sha384"  label="SHA384" key="sha384">
            <Input clearable v-model="formInline.sha384" type="textarea" :rows="3"></Input>
          </FormItem>
          <FormItem prop="sha512"  label="SHA512" key="sha512">
            <Input clearable v-model="formInline.sha512" type="textarea" :rows="3"></Input>
          </FormItem>
          <FormItem prop="sha3256"  label="SHA3 256" key="sha3256">
            <Input clearable v-model="formInline.sha3256" type="textarea" :rows="3"></Input>
          </FormItem>
          <FormItem prop="sha3512"  label="SHA3 512" key="sha3512">
            <Input clearable v-model="formInline.sha3512" type="textarea" :rows="3"></Input>
          </FormItem>
          <FormItem prop="announcements"  label="注意事项" key="announcements">
            <Input clearable v-model="formInline.announcements" type="textarea" :rows="3"></Input>
          </FormItem>
        </template>
        <template v-else-if="upgradeType === 'relevance'">
          <FormItem prop="partId" label="可选部件" class="my-form-item" key="partId">
            <Select filterable transfer filterable clearable v-model="formInline.partId" placeholder="">
              <Option v-for="item in optionList" :value="item.id" :key="item.id">{{ item.name }}({{ item.version }})</Option>
            </Select>
          </FormItem>
        </template>
      </Form>
      <div slot="footer" class="footer">
        <Button @click="modalData.show = false">取消</Button>
        <Button @click="saveProductPart" :loading="modalData.loading" type="primary">确定</Button>
      </div>
    </Modal>
    <Modal
      v-model="detailModalData.show"
      title="部件详情"
      footer-hide
      class="my-modal">
      <div class="item-table">
        <p>
          <span class='label'>部件名称</span>
          <span>{{detailInfo.name}}</span>
        </p>
        <p>
          <span class='label'>软硬件</span>
          <span>{{typeOptions[detailInfo.type]}}</span>
        </p>
        <template v-if="detailInfo.type === 0">
          <p>
            <span class='label'>软件包</span>
            <span>
              <Tooltip placement="top-start" transfer :max-width="200" :content="detailInfo.resSoftware.fileName" v-if="detailInfo.resSoftware">
                <a @click="downloadFile(detailInfo.resSoftware)">{{ detailInfo.resSoftware.fileName }}</a>
              </Tooltip>
              <span v-else></span>
            </span>
          </p>
          <p>
            <span class='label'>语言类型</span>
            <span>{{(detailInfo.resSoftware && detailInfo.resSoftware.language) | languageFilter}}</span>
          </p>
          <p>
            <span class='label'>包类别</span>
            <span>{{(detailInfo.resSoftware && detailInfo.resSoftware.type) | packageTypeFilter}}</span>
          </p>
        </template>
        <p>
          <span class='label'>供应商</span>
          <span>{{detailInfo.supplier}}</span>
        </p>
        <p>
          <span class='label'>部件类型</span>
          <span>{{(partTypeOptions.find(item => item.value === detailInfo.partType) || {}).label}}</span>
        </p>
        <p>
          <span class='label'>是否公共部件</span>
          <span>{{ detailInfo.isPublic === 'Y' ? '是' : '否' }}</span>
        </p>
        <p>
          <span class='label'>型号</span>
          <span>{{detailInfo.model}}</span>
        </p>
        <p>
          <span class='label'>版本</span>
          <span>{{detailInfo.version}}</span>
        </p>
        <p>
          <span class='label'>包URL</span>
          <span>{{detailInfo.groupAddress}}</span>
        </p>
        <p>
          <span class='label'>CPE名称</span>
          <span>{{detailInfo.enumItem}}</span>
        </p>
        <p>
          <span class='label'>软件标识标签</span>
          <span>{{detailInfo.swid}}</span>
        </p>
        <p>
          <span class='label'>对象标识</span>
          <span>{{detailInfo.objectId}}</span>
        </p>
        <p>
          <span class='label'>文件名称</span>
          <span>{{detailInfo.fileName}}</span>
        </p>
        <p>
          <span class='label'>描述</span>
          <span>{{detailInfo.description}}</span>
        </p>
        <p>
          <span class='label'>MD5</span>
          <span>{{detailInfo.md5}}</span>
        </p>
        <p>
          <span class='label'>SHA1</span>
          <span>{{detailInfo.sha1}}</span>
        </p>
        <p>
          <span class='label'>SHA256</span>
          <span>{{detailInfo.sha256}}</span>
        </p>
        <p>
          <span class='label'>SHA384</span>
          <span>{{detailInfo.sha384}}</span>
        </p>
        <p>
          <span class='label'>SHA512</span>
          <span>{{detailInfo.sha512}}</span>
        </p>
        <p>
          <span class='label'>SHA3 256</span>
          <span>{{detailInfo.sha3256}}</span>
        </p>
        <p>
          <span class='label'>SHA3 512</span>
          <span>{{detailInfo.sha3512}}</span>
        </p>
        <p>
          <span class='label'>注意事项</span>
          <span>{{detailInfo.announcements}}</span>
        </p>
      </div>
    </Modal>
    <relevance-part-module
      :productId="productId"
      :type="0"
      :isPublic="isPublic"
      hideButton
      ref="relevancPartModule"
      @relevance-success="getNewData"></relevance-part-module>
  </search-table>
</template>
<script>
import $ from 'jquery'
import encryption from '@/libs/encryption.js'
import { mapState } from 'vuex'
import { getImageData, deleteImage, getProfile, modifyImg, getDetailByID, getImageUserList, addAccess, modifyAccess, delAccess, mergeFiles, checkImage,getImageType } from '@/api/image.js'
import { getOperateInfo } from '@/api/target.js'
import { validateName128 } from '@/libs/reg'
import * as CommonFn from '../../common'
import resourcesReportedMixin from '@/mixin/resources-reported-mixin'
import pageTitle from '@/mixin/pageTitle';
import {queryProduct2, deleteProduct2, updateProduct2, addProduct, getNameUsedV2} from '../api/asset'
import { COMPONENT_TYPE_OPTIONS } from '@/view/testPlatform/paramsConfig.js'
import {getProductType, getUnitList, getVendorList, productPartTypeEscape} from "../logic/assetLogic";
import RelevancePartModule from '../../components/relevance-part-module'
import itemUpload from '../../components/item-upload/index.vue'
import {
  queryProductPartList,
  addProductPartNew,
  updateProductPartNew,
  deleteProductRelation,
  upgradePartByRelevance, addProductPart, updateProductPart, deleteProductPart
} from '../api/productPart'
export default {
  components: {RelevancePartModule,itemUpload},
  mixins: [resourcesReportedMixin,pageTitle],
  props: {
    productId: {
      type: String,
      default: ''
    },
    pagePos:{
      type:String,
      default: 'top'
    },
  },
  data () {
    return {
      isPublic: false,
      unitList:[],
      vendorList:[],
      assetCategoryList:[],
      partListLoading:false,
      partTotal:0,
      formInline: {
        name: '',
        partId: '',
        productId: this.productId,
        type: undefined,
        supplier: '',
        partType: undefined,
        model: '',
        version: '',
        groupAddress: '',
        enumItem: '',
        swid: '',
        objectId: '',
        fileName: '',
        description: '',
        md5: '',
        sha1: '',
        sha256: '',
        sha384: '',
        sha512: '',
        sha3256: '',
        sha3512: '',
        announcements: '',
        language: '',
        packageType: '',
        fileId: '',
        softwareFileName: '',
      },
      ruleInline: {
        name: [
          { required: true, message: '部件名称不能为空', trigger: 'blur,change' }
        ],
        type: [
          { required: true, type:'number', message: '软硬件不能为空', trigger: 'blur,change' }
        ],
        partType: [
          { required: true, type:'number', message: '类型不能为空', trigger: 'blur,change' }
        ],
        version: [
          { required: true, message: '版本号不能为空', trigger: 'blur,change' }
        ],
        partId: [
          { required: true, message: '可选部件不能为空', trigger: 'blur,change' }
        ],
        fileId:[
          { required: true, message: '请上传文件', trigger: 'blur,change' },
        ],
        language:[
          { required: true, type: 'number', message: '语言不能为空', trigger: 'blur,change' },
        ],
        packageType:[
          { required: true, type: 'number', message: '包类别不能为空', trigger: 'blur,change' },
        ],
      },
      partTypeOptions: COMPONENT_TYPE_OPTIONS,
      modalData: {
        show: false,
        loading: false
      },
      isAdd: false,
      upgradeType: 'add',
      typeOptions: ['软件', '硬件'],
      isUpgrade: false,
      file: {},
      optionList: [],
      detailModalData: {
        show: false
      },
      detailInfo: {},

      queryParams:{
        pageIndex:1,
        pageSize:10
      },
      // 用户信息
      USER_ID: '',
      isRootDesinger: '',
      distributed: false,
      // 页面设置
      fullHeight: document.documentElement.clientHeight,
      fullWidth: document.documentElement.clientWidth,
      setTableHei: 'auto',
      showDefImg: false,
      showImgList: false,
      // 镜像列表
      assetListLoading: false,
      assetCategory: [],
      unit: '',
      industry: '',
      assetTotal: 0,
      partList: [],
      partCol: [
        {
          title:'部件名称',
          key:'name',
          render:(h,params)=>{
            return h('Tooltip',{
              props:{
                content: params.row.name,
                transfer:true,
                placement: 'bottom-start',
                'max-width': 300
              },
            },[
              this.$route.query.productId?h('a',{
                on:{
                  click:()=>{
                    this.$router.push({
                      name: 'partDetail',
                      query: {
                        id: params.row.id,
                        assetName: this.$route.query.name,
                        productId: this.productId,
                        productGroupId:this.$route.query.productId,
                        partName:params.row.name,
                        isPublic: params.row.isPublic
                      }
                    })
                  }
                }
              }, params.row.name):h('span',params.row.name)
            ])
          }
        },

        {
          title:'版本',
          key:'version'
        },
        {
          title:'部件类型',
          key:'partType',
          render:(h,params)=>{
            let obj = this.partTypeOptions.find(item => item.value === params.row.partType) || {}
            return h('span',{
            }, obj.label)
          }
        },
        {
          title:'是否公共部件',
          key:'isPublic',
          render:(h,params)=>{
            return h('span',{
            }, params.row.isPublic === 'Y' ? '是' : '否')
          }
        },
        {
          title:'组件个数',
          key:'productComponentCount'
        },
        {
          title:'漏洞数',
          key:'componentMetricsVo',
          render:(h,params)=>{
            let { high, critical, low, medium, unassigned } = params.row.componentMetricsVo || {}
            return h('span', high + critical + low + medium + unassigned)
          }
        },
        {
          title:'风险评分',
          key:'lastInheritedRiskScore'
        },
        {
          title: '操作',
          width: 240,
          slot: 'action',
          opList: [
            {
              txt: '详情',
              on:{
                click:(data,e) => {
                  this.detailModalData.show = true
                 this.detailInfo = data
                }
              },
            },
            {
              txt: '修改',
              on:{
                click:(data,e) => {
                  this.showModal(data)
                }
              },
              disabled: (data) => data.isPublic === 'Y'
            },
            {
              txt: '升级',
              tooltip: true,
              title: '升级部件会删除原有部件的关联，并创建关联新的部件。',
              on:{
                click:(data,e) => {
                  this.showModal({id: obj.id, productPartRelation: data.productPartRelation}, true)
                }
              },
              disabled: (data) => data.isPublic === 'Y'
            },
            {
              txt: '下载',
              on:{
                click:(data,e) => {
                  this.downloadFile(data.resSoftware)
                }
              },
              disabled: (data)=>!(data.resSoftware && data.resSoftware.fileId) || false
            },
            {
              txt: '删除',
              tooltip: true,
              type: 'delete',
              title: '确定要删除这个部件吗？',
              on:{
                click:(data,e) => {
                 this.deleteItem(data.id)
                }
              },
            }
          ]
        },
      ],
      searchImageName: '',
      assetModelInput: '',
      creatByMeModal: false,
      // 创建和修改镜像
      imageID: '',
      assetModal: false,
      updateUrl: `/api/resource-manager/image/add`,
      addAssetBtnLoading: false,
      productTypeIds:[],
      assetFormData: {
        name:'',
        productTypeId:'',
        netinfoId:'',
        deviceType:0,
        vendorId:'',
        productOwnershipId: '',
        isSurvey:0,
        imageId:'',
        physicalDeviceCount:'1',
        flavorRef:'',
        model:'',
        version:'',
        description:'',
        logo:'',
        whiteBookFileId:'',
        productManualFileId:''
      },
      creatAssetRuleValidate: {
        name: [
          { required: true, message: '名称不能为空', trigger: 'change' },
          { max: 128, message: '名称长度不能超过128个字符', trigger: 'change' },
          { validator: validateName128, trigger: 'change' },
        ],
        version: [
          { required: true, message: '版本不能为空', trigger: 'blur' },
          {type:'string',max: 64,trigger:'blur',message:'最多输入64个字符'},
        ],
        vendorId: [
          { required: true, message: '请选择商家', trigger: 'change' }
        ],
        productOwnershipId: [
          { required: true, message: '请选择单位', trigger: 'change' }
        ],
        productTypeId:[
          { required: true,message: '请选择资产类型', trigger: 'change' }
        ],
        description: [
          { max: 200, message: '描述长度不能超过200个字符', trigger: 'change' },
        ],
      },
      speed: 0,
      loaded: 0,
      fileSize: 0,
      progress: 0,

      speedWhiteBook: 0,
      loadedWhiteBook: 0,
      fileSizeWhiteBook: 0,
      progressWhiteBook: 0,


      speedManualFileId: 0,
      loadedManualFileId: 0,
      fileSizeManualFileId: 0,
      progressManualFileId: 0,


      setDisabled: false,
      isCreate: true,
      //profile
      profileList: [],
      // 镜像用户
      showImgUser: false,
      formIsShow: false,
      imageUserId: '',
      addUserLoading: false,
      createPort: '22',
      isCreatUser: false,
      isClound: false,
      imgUserList: [],
      flag: 0, //标记成功的次数
      filedArr: [],//承装切片的容器
      oldTime: 0,//初始化时间
      progressflag: false,//控制进度条的展示
      fileName: '',
      saveTargetStatusArr: [],//存储中间状态
      messageSwitch: false,//解决鼠标移入失败或者成功验证状态气泡框位置错乱设置的开关
      systemVersion:[]
    }
  },
  computed: {
    formPartTypeOptions() {
      let list = []
      if (this.formInline.type === 1) { // 硬件只包含了设备一个选项
        list = [{
          label: '设备',
          value: 5
        }]
      } else if(this.formInline.type === 0) { // 屏蔽硬件与其他两个选项
        list = this.partTypeOptions.filter(item => ![0, 5].includes(item.value))
      } else {
        list = this.partTypeOptions.filter(item => ![0].includes(item.value))
      }
      return list
    }
  },
  filters: {
    packageTypeFilter(val) {
      switch(String(val)) {
        case '1': return 'JAVA'
        case '2': return 'GO'
        case '3': return 'PHP'
        case '4': return 'PYTHON'
        case '5': return 'C语言'
        case '6': return 'NODE.JS'
        case '7': return 'C++'
        case '99': return '其他'
        default: return ''
      }
    },
    languageFilter(val) {
      switch(String(val)) {
        case '1': return '源码'
        case '2': return '执行包'
        case '3': return '安装包'
        case '4': return '固件包'
        case '5': return '基线检测工具'
        case '6': return '补丁包'
        default: return ''
      }
    },
  },
  watch: {


  },
  created () {
    // 获取用户id
    let November = sessionStorage.getItem('November')
    November = JSON.parse(encryption.SelfUseDecrypt(November))
    this.USER_ID = November.userId
    this.isRootDesinger = November.isRootDesinger
    this.distributed = November.distributed
    // this.distributedRange = this.$store.state.user.distributedRange
  },
  mounted () {
    let getPage = this.$route.query.page ? parseInt(this.$route.query.page) : 1
    this.queryParams.pageIndex = getPage
    this.getNewData()
    getUnitList(this,'unitList');
    getVendorList(this,'vendorList');
    getProductType(this,'assetCategoryList')
  },
  methods: {
    getNewData(isRefresh){
      // 列表
      if (!isRefresh) { // 非刷新操作才需要展示等待中的画面
        this.partListLoading = true
      }
      if(this.$route.query.productId){
        this.queryParams.productId = this.productId;
      }else{
        this.queryParams.isPublic = 'N'
      }
      this.queryParams.vulNum=1
      queryProductPartList(this.queryParams)
        .then(res => {
          if (res.code == 1) {
            this.partTotal =res.data.total;
            this.partList = res.data.items
          }
          this.partListLoading = false
        })
        .catch(err => {
          this.partListLoading = false
        })
    },
    selectPart(){
      this.queryParams.pageIndex = 1;
      this.getNewData();
    },
    searchPartName(){
      this.queryParams.pageIndex = 1;
      this.getNewData();
    },
    relativePart(isPublic){
      this.isPublic = isPublic
      this.$nextTick(() => {
        this.$refs.relevancPartModule.showRelevanceModal()
      })
    },
    refreshPartList(){
      this.queryParams = {
        pageIndex:1,
        pageSize:10,
      }
      this.getNewData()
    },
    uploadSuccess(val){
      this.file = val
      //设置表单数据并触发表单检测
      this.$set(this.formInline, 'fileId', val.fileId)
      this.$set(this.formInline, 'softwareFileName', val.fileName)
      this.$refs.formInline.validateField('fileId');
    },
    setClear(){
      this.file = {}
      this.$set(this.formInline, 'fileId', '')
      this.$set(this.formInline, 'softwareFileName', '')
      this.$refs.formInline.validateField('fileId');
    },
    // 下载文件
    downloadFile(item) {
      if (!item.fileId) {
        return
      }
      let a = document.createElement('a');
      let fileName = item.fileName; //filename名称截取
      a.href = `/api/minio/download/${item.fileId}`;
      a.download = fileName; //命名下载名称
      a.click(); //点击触发下载
    },
    // 保存数据
    saveProductPart() {
      this.$refs.formInline.validate(valid => {
        if (valid) {
          this.modalData.loading = true
          let apiName;
          if(!this.$route.query.productId){
            apiName = this.isAdd ? addProductPart : updateProductPart
          }else{
            apiName = this.isAdd ? addProductPartNew : updateProductPartNew
          }
          if (this.formInline.type !== 0) {
            this.formInline.fileId = ''
            this.formInline.softwareFileName = ''
          }
          let {
            id,
            name,
            productId,
            type,
            supplier,
            partType,
            model,
            version,
            language,
            packageType,
            groupAddress,
            enumItem,
            swid,
            objectId,
            fileName,
            description,
            md5,
            sha1,
            sha256,
            sha384,
            sha512,
            sha3256,
            sha3512,
            announcements,
            fileId,
            softwareFileName,
            relationId,
            softwareId
          } = this.formInline;

          let data = {
            productPart: {
              id,
              announcements,
              category: 0,
              description,
              enumItem,
              fileName,
              groupAddress,
              md5,
              model,
              name,
              objectId,
              partType,
              productId,
              sha1,
              sha256,
              sha3256,
              sha3512,
              sha384,
              sha512,
              supplier,
              swid,
              type,
              version
            },
            productPartRelation: {
              id: relationId,
              productId
            },
            resSoftware: {
              fileId,
              fileName: softwareFileName,
              language,
              productId,
              type: packageType,
              id: softwareId
            }
          }
          if(!this.$route.query.productId){
            data = {...this.formInline};
            if(this.isAdd){
              delete this.formInline.id;
            }
          }
          // 升级时，额外传递oldProductPartRelationId字段
          if (this.isUpgrade) {
            data.oldProductPartRelationId = relationId
          }
          if (this.isUpgrade && this.upgradeType === 'relevance') { // 通过关联升级部件时，使用新的接口
            upgradePartByRelevance(relationId, this.formInline.partId).then(({ code, message }) => {
              if (code !== 1) {
                this.$Message.warning(message)
                return
              }
              // 创建成功
              this.$Message.success(`升级部件成功`)
              this.getNewData()
              this.modalData.show = false
            }).catch(() => {
              this.$Message.error(`升级部件异常`)
            }).finally(() => {
              this.modalData.loading = false
            })
          } else {
            apiName(data).then(({ code, message }) => {
              if (code !== 1) {
                this.$Message.warning(message)
                return
              }
              // 创建成功
              this.$Message.success(`${this.isUpgrade ? '升级' : this.isAdd ? '创建' : '修改'}部件成功`)
              this.getNewData()
              this.modalData.show = false
            }).catch(() => {
              this.$Message.error(`${this.isUpgrade ? '升级' : this.isAdd ? '创建' : '修改'}部件异常`)
            }).finally(() => {
              this.modalData.loading = false
            })
          }
        }
      })
    },

// 删除部件
    deleteItem(id) {
      if(!this.$route.query.productId){
        deleteProductPart([id]).then(res=>{
          if(res.code===1){
            this.$Message.success(`删除成功`)
            // 删除后展示当前页，当前页没有数据展示前一页
            this.queryParams.pageIndex = (this.partList.length === 1 && this.queryParams.pageIndex > 1) ?
              this.queryParams.pageIndex - 1 : this.queryParams.pageIndex;
            this.getNewData();
          }else{
            this.$Message.warning(res.message)
          }
        })
      }else{
        deleteProductRelation(this.productId, 0, id).then(({ code, message }) => {
          if (code !== 1) {
            this.$Message.warning(message)
            return
          }
          this.$Message.success(`删除成功`)
          // 删除后展示当前页，当前页没有数据展示前一页
          this.queryParams.pageIndex = (this.partList.length === 1 && this.queryParams.pageIndex > 1) ?
            this.queryParams.pageIndex - 1 : this.queryParams.pageIndex;
          this.getNewData();
        }).catch(() => {
          this.$Message.error(`删除部件异常`)
        })
      }

    },












    upload (file) {
      if (file.size <= 0) {
        this.$Message.error({
          content: '无效文件!',
          duration: 3
        })
        this.progressflag = false
        return
      }
      this.setDisabled = true //禁用选择文件按钮和提交按钮
      this.filedArr = []
      var clientId = this.generateClientId() //id
      var fileName = file.name;
      var size = file.size
      // if (file.size < 1024 * 1024 * 600) {
      // var shardSize = file.size; //如果上传的文件小于600M直接以当前文件为一个分片
      // } else {
      var shardSize = 1024 * 1024 * 50; //如果上传的文件大于600M就以50M为一个分片
      // }
      var chunks = Math.ceil(size / shardSize); //总片数
      for (var i = 0; i < chunks; ++i) {
        var start = i * shardSize; //计算每一片的起始位置
        var end = Math.min(size, start + shardSize)  //计算每一片的结束位置
        var partFile = file.slice(start, end)
        this.filedArr.push(partFile)
      };
      //上传分片请求函数
      const partUpload = async (clientId, filedArr, fileName, chunks, chunkId) => {
        try {
          let _this = this
          let partFile = filedArr[chunkId]
          var form = new FormData();
          form.append('clientId', clientId); //客户端id
          form.append('file', partFile); // slice方法 用于切出文件的一部分
          form.append('fileName', fileName); // 文件名
          form.append('chunks', chunks); // 总片数
          form.append('chunkId', chunkId); //当前是第几片
          const res = await _this.axios({
            method: 'post',
            url: `${this.baseURL}/resource-manager/upload/part`,
            data: form,
            headers: {
              'Content-type': 'multipart/form-data',
            },
            timeout:0,
            onUploadProgress: progressEvent => {
              if (file.size > 1024 * 1024) {
                this.fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB'
              } else {
                this.fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB'
              }
              this.fileName = file.name
              // if (file.size < 1024 * 1024 * 600) {
              //   var complete = Math.floor(progressEvent.loaded / progressEvent.total * 100)
              //   _this.progress = complete
              // }
              var newTime = +new Date()
              var DTime = (newTime - this.oldTime) / 1000
              this.oldTime = newTime

              var aaspeed = Number(progressEvent.loaded - _this.loaded) / (1024 * 1024)
              _this.loaded = progressEvent.loaded
              if (aaspeed / DTime < 1) {
                _this.speed = (Math.round(aaspeed / DTime * 1024 * 100) / 100).toString() + 'kB/s'
              } else {
                _this.speed = (Math.round(aaspeed / DTime * 100) / 100).toString() + 'MB/s'
              }
            },
          });
          if (res.data.code == 1) {
            chunkId += 1
            if (chunkId < this.filedArr.length) {
              _this.loaded = 0
              this.flag += 1
              var complete = Math.ceil(this.flag / chunks * 100)   //当前进度所占总进度的百分比
              this.progress = complete
              partUpload(clientId, this.filedArr, fileName, chunks, chunkId)
            } else {
              this.flag += 1
              var complete = Math.ceil(this.flag / chunks * 100)   //当前进度所占总进度的百分比
              this.progress = complete
              if (this.progress == 100) {
                this.setDisabled = false //打开提交和选择文件按钮权限
                _this.loaded = 0
                this.speed = 0//置空速度
                this.filedArr = []
                this.$Message.success({
                  content: '文件上传成功!',
                  duration: 3

                })
                // this.mergeFile(clientId,fileName) //不再调用合并分片接口，创建镜像的时候tempId为随机生成的clientId
                this.assetFormData.tempId = clientId
              }
            }
          }
        } catch (error) {
          console.log(error)
        }

      }
      partUpload(clientId, this.filedArr, fileName, chunks, 0)
    },
    //所有文件上传完毕之后的合并接口回调
    mergeFile (clientId, fileName) {
      var formMerge = new FormData();
      formMerge.append("clientId", clientId);
      formMerge.append("fileName", fileName);
      mergeFiles(formMerge)
        .then(res => {
            if (res.data.code == 1) {
              this.assetFormData.tempId = res.data.data
            }
          }
        ).catch(err => {
        this.$Message.error('合并文件出错')
      })
    },
    //文件的唯一ID
    generateClientId () {
      var counter = 0;
      var clientId = (+new Date()).toString(32),
        i = 0;
      for (; i < 5; i++) {
        clientId += Math.floor(Math.random() * 65535).toString(32);
      }
      return clientId + (counter++).toString(32);
    },
    // 打开模态框
    showModal(data, isUpgrade) {
      this.isUpgrade = isUpgrade ? isUpgrade : false
      if (this.isUpgrade) {
        this.getPartOptions()
      }
      this.isAdd = !data
      this.modalData.show = true
      let obj = data || {}
      this.formInline = Object.assign({ productId: this.productId }, obj)
      this.$nextTick(() => {
        let resSoftware = obj.resSoftware || {}
        let { fileId, language, type, fileName, id } = resSoftware
        if (fileId) {
          this.$refs.fileUpload && this.$refs.fileUpload.showDefaultList({fileName, filePath: fileId})
        } else {
          this.$refs.fileUpload && this.$refs.fileUpload.showDefaultList(null)
        }
        this.$set(this.formInline, 'packageType', type)
        this.$set(this.formInline, 'language', language)
        this.$set(this.formInline, 'relationId', obj.productPartRelation ? obj.productPartRelation.id : '')
        this.$set(this.formInline, 'softwareId', id)
        this.$set(this.formInline, 'fileId', fileId)
        this.$set(this.formInline, 'softwareFileName', fileName)
      })
    },
    // 打开关联部件的模态框，初始化数据
    getPartOptions() {
      Promise.all([queryProductPartList({
        pageIndex: 1,
        pageSize: 2147483646,
        productId: this.productId
      }), queryProductPartList({
        pageIndex: 1,
        pageSize: 2147483646,
      })]).then(res => {
        let selfIds = [], allOptionList = []
        res.forEach((item, index) => {
          let { code, data } = item
          if (index === 0) { // 本产品已有的部件
            if (code === 1) {
              selfIds = (data.items || []).map(item => item.id)
            }
          } else { // 其他部件
            if (code === 1) {
              allOptionList = data.items || []
            }
          }
        })
        this.optionList = allOptionList.filter(item => !selfIds.includes(item.id))
      })
    },
    // 隐藏模态框时，重置表单数据
    changeVisible(type) {
      if (!type) {
        this.$refs.formInline.resetFields()
        this.upgradeType = 'add'
        this.modalData.loading = false
      }
    },
  },
  beforeDestroy () {

  }
}
</script>
<style scoped>
.ios-alert {
  /* position: absolute;
        top: -44px;
        right: -404px; */
  color: orange;
  font-size: 16px;
  cursor: pointer;
}
.too {
  position: absolute;
  left: 113px;
  top: -1px;
}
.my-form-item {
  position: relative;


}
.my-form-item  /deep/ .ivu-form-item-content {
  display: flex;
}
.my-form-item  /deep/ .ios-alert {
  color: orange;
  font-size: 16px;
  cursor: pointer;
}
.my-form-item {
  position: relative;
}
.my-form-item /deep/ .ivu-form-item-content {
  display: flex;
}
.my-form-item /deep/ .ivu-form-item-content .ivu-checkbox-wrapper {
  margin-left: 10px;
  width: 66px;
}
.item-table {
  display: table;
  width: 100%;
  border: 1px solid #eee;
  table-layout: fixed;
  word-break: break-all;
}
.item-table p {
  display: table-row;
  line-height: 36px;
  text-align: center;
}
.item-table p span {
  display: table-cell;
  border-bottom: 1px solid #eee;
}
.ios-alert {
  /* position: absolute;
        top: -44px;
        right: -404px; */
  color: orange;
  font-size: 16px;
  cursor: pointer;
}
.too {
  position: absolute;
  left: 113px;
  top: -1px;
}
</style>
